package com.chicken.controller;

import com.chicken.entity.User;
import com.chicken.service.UserService;
import com.chicken.util.JWTUtil;
import com.chicken.util.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    UserService userService;

    @PostMapping("list")
    public Result list(@RequestBody User user) {
        List<User> list = userService.getList(user);
        return Result.success(list);
    }

    @PostMapping("login")
    public Result login(@RequestBody User user) {
        String realPassword = userService.getPassword(user.getUserName());
        if (realPassword == null || !realPassword.equals(user.getPassword())) {
            return Result.fail("用户名或密码错误!");
        } else {
            String token = JWTUtil.createToken(user.getUserName());
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return Result.success(map);
        }
    }

    @GetMapping("info")
    public Result getInfo(String token) {
        System.out.println("token = " + token);
        String userName = JWTUtil.getUserName(token);
        System.out.println("userName = " + userName);
        User user = userService.getInfo(userName);
        return Result.success(user);
    }

    @PostMapping("logout")
    public Result logout() {
        return Result.success("注销成功!");
    }


}
